const API_BASE = 'https://tihaidengta.xyz';

Page({
  data: {
    user: wx.getStorageSync('user') || {},
    showEdit: false,
    account: '',
    editAvatar: '',
    editName: '',
    hasLogin: false ,// 默认未登录
  },

  onLoad() {
    const user = wx.getStorageSync('user') || {};
     // 从 user 中提取 account 字段（如果没有则为空字符串）
     const storedAccount = user.account || '';
    this.setData({
      user,
      account: storedAccount,
      editName: user.name || '',
      editAvatar: user.avatar || ''
    });
  },

  onShow() {
    const user = wx.getStorageSync('user');
    const storedAccount = user.account || '';
    const hasLogin = user && user.userId;
  this.setData({ 
    user: user || null,
    account: storedAccount,
    hasLogin
  });
  },

  // 进入编辑模式
  editProfile() {
    if (!this.data.user) return;
    this.setData({
      showEdit: true,
      editAvatar: this.data.user.avatar,
      editName: this.data.user.name
    });
  },
//  // 👇 自动提交昵称
//  autoSubmitNickname() {
//   const form = this.selectComponent('#nicknameForm');
//   if (form) {
//     form.submit();
//   }
// },
 // 👇 接收微信昵称
 onNicknameSubmit(e) {
  const nickname = e.detail.value.nickname;
  if (nickname) {
    this.setData({
      editName: nickname
    });
    wx.showToast({ title: '昵称已获取', icon: 'success' });
  }
},

// 选择头像
onChooseAvatar(e) {
  const tempPath = e.detail.avatarUrl;
  const fs = wx.getFileSystemManager();
  const fileName = `avatar_${Date.now()}.png`;
  const localPath = `${wx.env.USER_DATA_PATH}/${fileName}`;

  // 始终复制头像到可上传的本地用户路径
  fs.copyFile({
    srcPath: tempPath,
    destPath: localPath,
    success: () => {
      this.setData({
        editAvatar: localPath
      });
      wx.showToast({ title: '头像准备就绪', icon: 'success' });
    },
    fail: (err) => {
      console.error('头像复制失败:', err);
      wx.showToast({ title: '头像复制失败', icon: 'none' });
    }
  });
}
,
  // 输入昵称
  onNameInput(e) {
    this.setData({
      editName: e.detail.value
    });
  },

 // 👇 提交修改资料（昵称 & 头像）
 submitProfile() {
  const { editAvatar, editName, user } = this.data;

  if (!user || !user.openid || !user.userId) {
    wx.showToast({ title: '用户信息缺失，请重新登录', icon: 'none' });
    return;
  }

  const { openid, userId } = user;

  const updateData = {
    userId,
    openid
  };

  const isNameChanged = editName !== user.name && editName;
  if (isNameChanged) {
    updateData.name = editName;
  }

  const isAvatarChanged = editAvatar !== user.avatar && !editAvatar.startsWith('https');

  if (!isNameChanged && !isAvatarChanged) {
    wx.showToast({ title: '你没有修改任何信息', icon: 'none' });
    return;
  }

  // 头像未变 → 只上传昵称
  if (!isAvatarChanged) {
    return this.updateUserInfo(updateData);
  }


    // 如果头像改了
    // console.log('上传头像路径:', editAvatar);
    wx.uploadFile({
      url: `${API_BASE}/eduservice/user/uploadUserImage`,
      filePath: editAvatar,
      name: 'file',
      header: {
        'Authorization': wx.getStorageSync('token') || ''
      },
      success: (uploadRes) => {
        let uploadData;
        try {
          // 使用 JSON.parse 解析返回的字符串
          uploadData = JSON.parse(uploadRes.data);
        } catch (err) {
          console.error('❌ JSON 解析失败:', err);
          wx.showToast({ title: '头像上传解析失败', icon: 'none' });
          return;
        }
    
        const uploadedUrl = uploadData.data?.url;
    
        if (uploadData.code === 20000 && uploadedUrl) {
          updateData.avatar = uploadedUrl;
          this.updateUserInfo(updateData);
        } else {
          wx.showToast({ title: '头像上传失败', icon: 'none' });
        }
      },
    
      // ❗ 修复 fail 回调中 err 未定义的问题
      fail: (err) => {
        console.error('❌ 上传头像失败:', err);
        wx.showToast({ title: '头像上传失败', icon: 'none' });
      }
    });
  },

  // 调用后端接口更新用户数据
  updateUserInfo(updateData) {
    wx.request({
      url: `${API_BASE}/eduservice/user/updateUser`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || ''
      },
      data: updateData,
      success: (res) => {
        if (res.statusCode === 200) {
          const newUser = {
            ...this.data.user,
            ...updateData
          };
          wx.setStorageSync('user', newUser);
          this.setData({
            user: newUser,
            showEdit: false
          });
          wx.showToast({ title: '更新成功', icon: 'success' });
        } else {
          wx.showToast({ title: '更新失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 取消编辑
  cancelEdit() {
    this.setData({
      showEdit: false
    });
  },

  // 退出登录
  handleUserTap() {
    if (this.data.user) {
      wx.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            wx.removeStorageSync('user');
            this.setData({ user: null });
            wx.showToast({ title: '已退出登录', icon: 'success' });
          }
        }
      });
    }
  },

  // 跳转登录页
  goToLogin() {
    wx.navigateTo({
      url: '/subpackage/user/logn/logn'
    });
  },

  goToSettings() {
    wx.navigateTo({
      url: '/subpackage/user/settings/index'
    });
  },

  goToFAQ() {
    wx.navigateTo({
      url: '/subpackage/user/faq/index'
    });
  },
  goTogenerate(){
    wx.navigateTo({
      url: '/subpackage/user/generate/generate',
    });
  },
  // goToContact() {
  //   wx.navigateTo({
  //     url: '/subpackage/user/contact/index'
  //   });
  // },

  goToFeedback() {
    wx.navigateTo({
      url: '/subpackage/user/feedback/feedback'
    });
  },
  goToJiHuo() {
    // 方法1：如果是 tabBar 页面，使用 switchTab
    wx.switchTab({
      url: '/pages/jihuoma/jihuoma' // 确保路径正确
    });
  },
  onShareAppMessage(){},
  onShareTimeline(){}
});
